#include "server.h"

TCPServer::TCPServer(int port):port(port),server_fd(-1),client_fd(-1){}

TCPServer::~TCPServer()
{
    if(server_fd != -1)
    {
        close(server_fd);
        server_fd = -1;
    }
    if(client_fd != -1)
    {
        close(client_fd);
        client_fd = -1;
    }
}

bool TCPServer::start()
{
    server_fd = socket(AF_INET,SOCK_STREAM,0);
    if(server_fd == -1)
    {
        cerr << "Failed to create socket" << endl;
        return false;
    }
    // 配置服务器地址结构
    sockaddr_in server_addr;
    server_addr.sin_family = AF_INET;         // IPv4
    server_addr.sin_port = htons(port);       // 端口号
    server_addr.sin_addr.s_addr = INADDR_ANY; // 任意地址

    // 绑定服务器地址结构
    if(bind(server_fd,(sockaddr*)&server_addr,sizeof(server_addr)) == -1)
    {
        cerr << "Failed to bind socket" << endl;
        close(server_fd);
        return false;
    }

    // 监听 最多允许3个连接请求等待队列
    if(listen(server_fd,3) == -1)
    {
        cerr << "Failed to listen socket" << endl;
        close(server_fd);
        return false;
    }

    cout << "Server started on port " << port << endl;
    return true;
}

bool TCPServer::acceptclient()
{
    sockaddr_in client_addr;
    socklen_t client_len = sizeof(client_addr);

    // 接收客户端连接请求，阻塞等待直到有连接到达
    client_fd = accept(server_fd,(sockaddr*)&client_addr,&client_len);
    if (client_len == -1)
    {
        cerr << "Failed to accept client connection" << endl;
        return false;
    }
    cout << "Client connected" << endl;
    return true;
}

bool TCPServer::recvdata(string &data)
{
    // 检测是否有客户端连接
    if (client_fd == -1)
    {
        cerr << "No client connected" << endl;
        return false;
    }
    // 接收缓冲区
    char buffer[1024] = {0};
    // 接收客户端数据
    ssize_t bytesReceived = recv(client_fd, buffer, sizeof(buffer), 0);
    if(bytesReceived == -1)
    {
        cerr << "receive data failed" << endl;
        return false;
    }
    data = string(buffer, bytesReceived);
    cout << "Received data from client: " << buffer << endl;
    return true;
}

bool TCPServer::senddata(const string &data)
{
    // 检测是否有客户端连接
    if (client_fd == -1)
    {
        cerr << "No client connected" << endl;
        return false;
    }
    // 发送数据
    ssize_t bytesend = send(client_fd,data.c_str(),data.size(),0);
    if (bytesend == -1)
    {
        cerr << "send data failed" << endl;
        return false;
    }
    cout << "Send data to client" << endl;
    return true;
}

TCPServer &TCPServer::operator<<(const string &data)
{
    senddata(data);
    return *this;
}

TCPServer &TCPServer::operator>>(string &data)
{
    recvdata(data);
    return *this;
}

void TCPServer::closeserver()
{
    if(server_fd != -1)
    {
        close(server_fd);
        server_fd = -1;
    }
    if(client_fd != -1)
    {
        close(client_fd);
        client_fd = -1;
    }
}